from django import forms
from apps.base.models import User
from service.encrypt import md5
from django.conf import settings


class UserAddForm(forms.ModelForm):
    """用户新增"""
    password = forms.CharField(label="密码")
    repassword = forms.CharField(label="重复密码")
    password_hash = forms.CharField(label="hash密码", required=False)

    class Meta:
        model = User
        fields = ['nickname', 'username', 'email', 'avatar', 'postion', 'gender', 'is_enabled',
                  'department', 'password', 'repassword', 'password_hash']

    # def clean(self):
    #     if self.errors:
    #         return self.cleaned_data
    #     # 1. 若头像为空, 则使用默认头像 - 设置媒体文件路径
    #     if not self.cleaned_data.get('avatar'):
    #         self.cleaned_data['avatar'] = settings.DEFAULT_AVATAR
    #     # 2. 两次密码需一致，一致后hash加密
    #     password = self.cleaned_data.get('password')
    #     repassword = self.cleaned_data.get('repassword')
    #     if password != repassword:
    #         raise forms.ValidationError("两次密码输入不一致")
    #     self.cleaned_data["password_hash"] = md5(password)
    #     # 3. 手机号和邮箱不能重复
    #     mobile = self.cleaned_data.get('mobile')
    #     email = self.cleaned_data.get('email')
    #     if User.objects.filter(mobile=mobile).exists():
    #         raise forms.ValidationError("手机号已存在")
    #     if User.objects.filter(email=email).exists():
    #         raise forms.ValidationError("邮箱已存在")
    #     return self.cleaned_data


class UserEditForm(forms.ModelForm):
    """用户编辑"""

    class Meta:
        model = User
        fields = ['nickname', 'username', 'mobile', 'email', 'avatar', 'postion', 'gender', 'is_enabled', 'department']


class ResetPwdForm(forms.ModelForm):
    """重置密码"""
    password = forms.CharField(label="密码")
    repassword = forms.CharField(label="重复密码")
    password_hash = forms.CharField(label="hash密码", required=False)

    class Meta:
        model = User
        fields = ['password', 'repassword', 'password_hash']

    def clean(self):
        if self.errors:
            return self.cleaned_data
        # 两次密码需一致，一致后hash加密
        password = self.cleaned_data.get('password')
        repassword = self.cleaned_data.get('repassword')
        if password != repassword:
            raise forms.ValidationError("两次密码输入不一致")
        self.cleaned_data["password_hash"] = md5(password)
        return self.cleaned_data


class UserInfoForm(forms.ModelForm):
    """个人中心 -- 用户基本信息的修改"""

    class Meta:
        model = User
        fields = ['nickname', 'username', 'email', 'avatar', 'sign', 'gender']
